# !usr/bin/env python
# -*- coding:utf-8 -*-

""" 数据库工具类
 Description  :
 Version      : 1.0
 Author        : qww
 Date         : 2021-05-02 16:57:13
 LastEditors  : qww
 LastEditTime : 2021-05-02 19:32:00
"""

import pymysql
from utils.singleton import singleton


@singleton
class DBUtil:
    """
        数据库工具类
        host：主机名
        user: 用户名
        password:密码
        database: 数据库名称
        port: 端口号
        conn: 数据库连接
        cursor: 获取游标句柄
    """
    cursor = ''  # 句柄
    conn = ''  # 打开数据库连接

    def __init__(self, host: str, user: str, password: str, database: str, port: int=3306):

        self.__host = host
        self.__user = user
        self.__password = password
        self.__database = database
        self.__port = port

        self.conn = pymysql.connect(host=self.__host, user=self.__user,
                                    password=self.__password, database=self.__database,
                                    port=self.__port, charset="utf8")
        self.cursor = self.conn.cursor()

    # 获取所有的结果集
    def queryAll(self, sql, args=None):
        self.cursor.execute(sql, args)
        results = self.cursor.fetchall()
        return results

    # 获取一条记录
    def queryOne(self, sql, args=None):
        self.cursor.execute(sql, args)
        results = self.cursor.fetchone()
        return results

    # 插入或更新数据
    def saveOne(self, sql, args=None):
        try:
            # 执行SQL语句
            self.cursor.execute(sql, args)
            # 提交到数据库执行
            self.conn.commit()
        except:
            # 发生错误时回滚
            self.conn.rollback()
        # 返回受影响的行数
        return self.cursor.rowcount

    # 关闭链接
    def close(self):
        self.conn.close()



